package com.pfzy.utildemo.activity.record.soundrecord;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.pfzy.lib.config.log.MyLog;
import com.pfzy.utildemo.activity.record.sdk.pcm.RecordHelper;
import com.pfzy.utildemo.activity.record.soundrecord.constatns.CallbackConstant;
import com.pfzy.utildemo.activity.record.soundrecord.db.AudioFileInfo;
import com.pfzy.utildemo.activity.record.soundrecord.helper.CallBackHelper;

/**
 * 录音服务
 */
public class RecordingService extends Service {
    public static final String ACTION_START_RECORD = "start_sound_record";
    public static final String ACTION_STOP_RECORD = "stop_sound_record";
    public static final String KEY_TRANSMIT_DATA_TO_SERVICE = "sound_record_key_transmit_data_to_service";
    private Handler mHandler = new Handler(Looper.getMainLooper());

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        RecordingInfo recordingInfo = intent.getParcelableExtra(KEY_TRANSMIT_DATA_TO_SERVICE);
        if (TextUtils.equals(intent.getAction(), ACTION_START_RECORD)) {
            startRecord(recordingInfo);
            return Service.START_NOT_STICKY;// service如果被干掉，不会再自动重启
        } else if (TextUtils.equals(intent.getAction(), ACTION_STOP_RECORD)) {
            stopRecord(recordingInfo);
            return Service.START_NOT_STICKY;
        } else {
            return Service.START_NOT_STICKY;
        }
    }

    @Override
    @Nullable
    public IBinder onBind(Intent intent) {
        _logd("onBind()");
        return null;
    }

    @Override
    public void onRebind(Intent intent) {
        _logd("onRebind()");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        _logd("onUnbind()");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        _logd("onDestroy()");
        stopRecord();
        super.onDestroy();
        SoundFileSplitUpload.getInstance().destroy();
        this.mHandler.removeCallbacksAndMessages(null);
    }

    private void startRecord(RecordingInfo mRecordingInfo) {
        this.mHandler.removeCallbacksAndMessages(null);
        _logd("enter startRecord()");
        if (mRecordingInfo != null) {
            if (RecordHelper.getInstance().isRecording()) {
                _loge("startRecord() 当前正在录音，确重新调用开始");
                return;
            }

            // 开始录音 并 设置正在录制种
            CallBackHelper.execOnStartAndSetIsRecording(mRecordingInfo);
            try {
                SoundFileSplitUpload.getInstance().setNewRecordingInfo(mRecordingInfo);
                AudioFileInfo mAudioFileInfo = SoundFileSplitUpload.getInstance().getNewRecordingFile();
                _logd("startRecord() -- mAudioFileInfo=" + mAudioFileInfo);
                RecordHelper.getInstance().startRecord(mAudioFileInfo.getAudioFilePath(), mRecordingInfo);
                SoundFileSplitUpload.getInstance().startSplitTask();
            } catch (Exception e) {
                _loge("startRecord() 发生异常 " + e);
                CallBackHelper.execOnStopAndClearAndSetIsRecording(mRecordingInfo, CallbackConstant.StopInfo.FILE_EXCEPTION, e);
            }
        }
    }

    private void stopRecord(RecordingInfo recordingInfo) {
        _logd("onStopRecordingEvent() = " + recordingInfo);
        if (!RecordHelper.getInstance().isRecording()) {
            _logd("stopRecord()  当前不在录音. 确调用stop");
            return;
        }
        RecordingInfo mRecrodInfo = RecordHelper.getInstance().getCurrentRecordInfo();
        if (recordingInfo == null || mRecrodInfo == null) {
            stopRecord();
        } else if (TextUtils.equals(recordingInfo.getOrderNo(), mRecrodInfo.getOrderNo()) && TextUtils.equals(recordingInfo.getUid(), mRecrodInfo.getUid())) {
            stopRecord();
        } else {
            _logd("虽然调用了结束，但是确并不是当前 订单信息");
        }
    }

    private void stopRecord() {
        _logd("enter stopRecord()");
        if (!RecordHelper.getInstance().isRecording()) {
            _logd("stopRecord()  当前不在录音. 确调用stop");
            return;
        }
        SoundFileSplitUpload.getInstance().updateFileInfo2RecordDone();
        RecordHelper.getInstance().stopRecord();
        CallBackHelper.execOnStopAndClearAndSetIsRecording(RecordHelper.getInstance().getCurrentRecordInfo(), CallbackConstant.StopInfo.NORMAL_STOP);
        this.mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopSelf();
            }
        }, 300000L);
    }

    private void _logd(String msg) {
        MyLog.logd("录音服务 " + msg);
    }
    private void _loge(String msg) {
        MyLog.loge("录音服务 " + msg);
    }
}
